package com.disease.chronic.Listener;

import com.disease.chronic.Component.AlertWebSocket;
import com.disease.chronic.Component.DeviceStatusWebSocket;
import com.disease.chronic.Component.IndicatorWebSocket;
import com.disease.chronic.Mappers.IndicatorsDetailMapper;
import com.disease.chronic.Mappers.IndicatorsMapper;
import com.disease.chronic.Service.DeviceService;
import com.disease.chronic.Service.FamilyService;
import com.disease.chronic.Service.MSMService;
import com.disease.chronic.Service.UserService;
import com.disease.chronic.dto.AmqpTemplateDto;
import com.disease.chronic.dto.BloodPressureDto;
import com.disease.chronic.pojo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.sql.Date;
import java.util.Arrays;
import java.util.List;


@Slf4j
@Component
//监听另一个服务器的消息队列
public class MessageListener {

    @Autowired
    DeviceService deviceService;
    @Autowired
    IndicatorsMapper indicatorsMapper;
    @Autowired
    MSMService msmService;

    @Autowired
    UserService userService;

    @Autowired
    FamilyService familyService;

    @Autowired
    IndicatorsDetailMapper indicatorsDetailMapper;

    @RabbitListener(queues = {"BloodPressure"})
    public void sendMessage(String message) throws IOException {
        //按约定好的格式分割
        String[] split = message.split(",");
        String deviceId = split[0].replaceAll("\"","");
        String sPressure_ = split[1];
        String dPressure_ = split[2];
        BloodPressureDto bloodPressureDto = new BloodPressureDto(deviceId,sPressure_, dPressure_);

        String username = deviceService.getUsername(bloodPressureDto.getDeviceId());//根据设备id查出所属用户

        //收缩压的查询
        IndicatorsDetail indicatorsDetail = indicatorsDetailMapper.
                selectByUsernameAndIndicatorNameAndDay(username,"收缩压",
                        new Date(System.currentTimeMillis()));         //查询当天有没有测量，有则覆盖


        //查询收缩压指标
        Indicators sPressure_indicator = indicatorsMapper.selectByUsernameAndIndicatorName(username, "收缩压");
        //更新最后一次测量日期和数值
        if(sPressure_indicator!=null){
            sPressure_indicator.setLastUpdateTime(new Date(System.currentTimeMillis()));
            sPressure_indicator.setLastMeasure(bloodPressureDto.getSPressure());

            indicatorsMapper.updateByPrimaryKey(sPressure_indicator);
        }else{
            //不存在则新建再插入
            sPressure_indicator = new Indicators();
            sPressure_indicator.setLastUpdateTime(new Date(System.currentTimeMillis()));
            sPressure_indicator.setLastMeasure(bloodPressureDto.getSPressure());
            sPressure_indicator.setIndicatorUnit("mmHg");
            sPressure_indicator.setIndicatorName("收缩压");
            sPressure_indicator.setUsername(username);
            sPressure_indicator.setNormalScope("90-140");
            indicatorsMapper.insert(sPressure_indicator);
        }

        if(indicatorsDetail == null){
            //存储进数据库
            IndicatorsDetail sPressure = new IndicatorsDetail();
            sPressure.setUsername(username);
            sPressure.setIndicatorName("收缩压");
            sPressure.setDay(new Date(System.currentTimeMillis()));
            sPressure.setValue(bloodPressureDto.getSPressure());//设置指标值
            indicatorsDetailMapper.insert(sPressure);

        }else {
            //存在则更新收缩压
            indicatorsDetail.setValue(bloodPressureDto.getSPressure());
            indicatorsDetail.setDay(new Date(System.currentTimeMillis()));
            indicatorsDetailMapper.updateByPrimaryKey(indicatorsDetail);
        }


        IndicatorsDetail dPressureDetail = indicatorsDetailMapper.
                selectByUsernameAndIndicatorNameAndDay(username,"舒张压",
                        new Date(System.currentTimeMillis()));

        //查询收缩压指标
        Indicators dPressure_indicator = indicatorsMapper.selectByUsernameAndIndicatorName(username, "舒张压");
        //更新最后一次测量日期和数值
        if(dPressure_indicator !=null){
            dPressure_indicator.setLastUpdateTime(new Date(System.currentTimeMillis()));
            dPressure_indicator.setLastMeasure(bloodPressureDto.getDPressure());

            indicatorsMapper.updateByPrimaryKey(dPressure_indicator);
        }else{
            //不存在则新建再插入
            dPressure_indicator = new Indicators();
            dPressure_indicator.setLastUpdateTime(new Date(System.currentTimeMillis()));
            dPressure_indicator.setLastMeasure(bloodPressureDto.getDPressure());
            dPressure_indicator.setIndicatorUnit("mmHg");
            dPressure_indicator.setIndicatorName("收缩压");
            dPressure_indicator.setUsername(username);
            dPressure_indicator.setNormalScope("60-90");
            indicatorsMapper.insert(dPressure_indicator);
        }
        if(dPressureDetail == null){
            //存储进数据库
            IndicatorsDetail dPressure = new IndicatorsDetail();
            dPressure.setUsername(username);
            dPressure.setIndicatorName("舒张压");
            dPressure.setDay(new Date(System.currentTimeMillis()));
            dPressure.setValue(bloodPressureDto.getDPressure());//设置指标值
            indicatorsDetailMapper.insert(dPressure);
        }else{
            //存在则更新舒张压
            dPressureDetail.setValue(bloodPressureDto.getDPressure());
            dPressureDetail.setDay(new Date(System.currentTimeMillis()));
            indicatorsDetailMapper.updateByPrimaryKey(dPressureDetail);
        }


        int sPressure = Integer.parseInt(bloodPressureDto.getSPressure());
        int dPressure = Integer.parseInt(bloodPressureDto.getDPressure());

        if(sPressure<140&&sPressure>90&&dPressure<90&&dPressure>60){
            AlertWebSocket.alert(username,"收缩压/舒张压",
                    bloodPressureDto.getSPressure()+"/"+bloodPressureDto.getDPressure(), 0);
        }else{
            AlertWebSocket.alert(username,"收缩压/舒张压",
                    bloodPressureDto.getSPressure()+"/"+bloodPressureDto.getDPressure(), 1);

            User user = userService.getUser(username);
            //查询所有关联的家属手机号，推送报警短信
            List<Family> families = (List<Family>) familyService.getFamily(username).getData();
            for(Family i:families){

                msmService.send(i.getPhoneNumber());
            }


        }

        //向指标页面推送最新数据
        IndicatorWebSocket.sendMessage(username,"收缩压",bloodPressureDto.getSPressure());
        IndicatorWebSocket.sendMessage(username,"舒张压",bloodPressureDto.getDPressure());

    }
    @RabbitListener(queues = {"amqpTemplate"})
    public void tempMessage(String message) throws IOException {
        String[] split = message.split(",");
        String deviceId = split[0].replaceAll("\"","");
        String temp_ = split[1];
        AmqpTemplateDto templateDto= new AmqpTemplateDto(deviceId,temp_);
        String username = deviceService.getUsername(templateDto.getDeviceId());//根据设备id查出所属用户

        //查询今日是否已经测量
        IndicatorsDetail indicatorsDetail = indicatorsDetailMapper.
                selectByUsernameAndIndicatorNameAndDay(username,"体温",
                        new Date(System.currentTimeMillis()));
        //无则插入，有则更新
        if(indicatorsDetail == null){
            //如果没有该测量值则新插入
            indicatorsDetail = new IndicatorsDetail();
            indicatorsDetail.setIndicatorName("体温");
            indicatorsDetail.setDay(new Date(System.currentTimeMillis()));
            indicatorsDetail.setValue(templateDto.getAmqpTemplate());
            indicatorsDetail.setUsername(username);
            indicatorsDetailMapper.insert(indicatorsDetail);

        }else {
            indicatorsDetail.setValue(templateDto.getAmqpTemplate());
            indicatorsDetailMapper.updateByPrimaryKey(indicatorsDetail);
        }


        Indicators temp = indicatorsMapper.selectByUsernameAndIndicatorName(username, "体温");
        //如果用户是第一次测试该指标则新建
        if(temp == null){
            temp = new Indicators();
            temp.setNormalScope("36-37");
            temp.setUsername(username);
            temp.setIndicatorUnit("℃");
            temp.setLastMeasure(templateDto.getAmqpTemplate());
            temp.setLastUpdateTime(new Date(System.currentTimeMillis()));
            temp.setIndicatorName("体温");
            indicatorsMapper.insert(temp);
        }else{
            temp.setLastUpdateTime(new Date(System.currentTimeMillis()));
            temp.setLastMeasure(templateDto.getAmqpTemplate());
            indicatorsMapper.updateByPrimaryKey(temp);
        }

        //体温转成浮点。
        double t = Double.parseDouble(templateDto.getAmqpTemplate());
        if(t>=36&&t<=37){
            AlertWebSocket.alert(username,"体温",templateDto.getAmqpTemplate(),0);
        }else{

            AlertWebSocket.alert(username,"体温",templateDto.getAmqpTemplate(),1);
            User user = userService.getUser(username);
            //查询所有关联的家属手机号，推送报警短信
            List<Family> families = (List<Family>) familyService.getFamily(username).getData();
            for(Family i:families){
                System.out.println(i.getPhoneNumber());
                msmService.send(i.getPhoneNumber());
            }
        }


        //向指标页面的webSocket推送数据
        IndicatorWebSocket.sendMessage(username,"体温",templateDto.getAmqpTemplate());



    }

    @RabbitListener(queues = {"DeviceStatus"})
    //message= deviceId+","+status
    public void deviceStateMessage(String message) throws IOException {
        String[] split = message.split(",");
        String deviceId = split[0].replaceAll("\"","");
        String status = split[1].replaceAll("\"","");

        log.info("接收到的状态信息"+Arrays.toString(split));

        Device device = deviceService.getDeviceInfoByDeviceId(deviceId);
        String deviceName = device.getName();
        String username = device.getUsername();
        deviceService.setDeviceStatus(deviceId,status);

        if(split[1].contains("ON"))
            DeviceStatusWebSocket.setStatus(username,deviceName,1);
        else {

            DeviceStatusWebSocket.setStatus(username,deviceName,0);
        }

    }

}
